package com.adlx.dingdong.mall.controller;

import com.adlx.dingdong.mall.user.api.UserFeignClient;
import com.adlx.dingdong.mall.user.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

@Slf4j
public class BaseController {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }


    /**
     * 从Oauth认证获取用户ID
     *
     * @return
     */
    public Integer getCurrentUid() {
        String userName = SecurityContextHolder.getContext().getAuthentication().getName();
        log.info("授权认证用户：" + userName);
        UserDTO user = userFeignClient.getUserByUsername(userName);
        return user != null ? user.getId().intValue() : null;
    }

    /**
     * 客户验证
     *
     * @param request
     * @return
     */
    protected Boolean checkOauthClient(HttpServletRequest request) {
        Enumeration headers = request.getHeaders("Authorization");
        String value;
        do {
            if (!headers.hasMoreElements()) {
                return false;
            }
            value = (String) headers.nextElement();
        } while (!value.toLowerCase().startsWith("Basic".toLowerCase()));

        String clientIdValue = value.substring("Basic".length()).trim();
        byte[] encodeBase64 = Base64.decode(clientIdValue.getBytes());
        String client = new String(encodeBase64);
        String[] clientId = client.split(":");
        log.info("RESULT: " + clientId[0]);
        try {
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId[0]);
            if (null != clientDetails && clientId.length == 2 && clientDetails.getClientSecret().equals(clientId[1])) {
                return true;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }


}
